package org.aeon.gamechatnest.service.impl;

import org.aeon.gamechatnest.common.enumeration.LoginStatus;
import org.aeon.gamechatnest.common.response.RespStatus;
import org.aeon.gamechatnest.common.response.ResultBuild;
import org.aeon.gamechatnest.dto.UserVo;
import org.aeon.gamechatnest.exception.ApplicationException;
import org.aeon.gamechatnest.mapper.FriendMapper;
import org.aeon.gamechatnest.mapper.FriendRequestMapper;
import org.aeon.gamechatnest.pojo.Friend;
import org.aeon.gamechatnest.pojo.FriendRequest;
import org.aeon.gamechatnest.service.FriendService;
import org.aeon.gamechatnest.service.UserService;
import org.aeon.gamechatnest.util.RedisCache;
import org.aeon.gamechatnest.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 好友管理服务类
 *
 * @author : Qik 2024/5/9 15:19
 */
@Service
public class FriendServiceImpl implements FriendService {
    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private FriendRequestMapper friendRequestMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 根据好友请求与登录用户，创建好友关系（带验证）
     *
     * @param friendRequest 好友请求
     * @param loginUserId   登录用户id
     * @return 好友实体
     */
    protected static Friend getFriend(FriendRequest friendRequest, Long loginUserId) {
        Integer verifyStatus = friendRequest.getVerifyStatus();
        Long fromUser = friendRequest.getFromUser();
        Long toUser = friendRequest.getToUser();
        // 校验是发给登录用户的请求
        if (!toUser.equals(loginUserId)) {
            ResultBuild.result().state(RespStatus.NO_PERMISSION).message("好友请求接收者与当前登录用户不符");
            return null;
        }

        // 好友请求状态不为0：未处理
        if (verifyStatus != 0) {
            ResultBuild.result().state(RespStatus.PARAM_ERROR).message("好友请求已处理，请勿重复操作");
            return null;
        }

        // 创建好友
        Friend friend = new Friend();
        friend.setFromUser(fromUser);
        friend.setToUser(toUser);
        friend.setCreateTime(new Date());
        return friend;
    }

    @Override
    @Transactional(rollbackFor = ApplicationException.class)
    public boolean agree(Long id) {
        // 获取登录用户id
        Long loginUserId = SecurityUtil.getUserId();

        // 获取好友请求
        FriendRequest friendRequest = friendRequestMapper.getById(id);
        // 好友请求不存在
        if (friendRequest == null) {
            ResultBuild.result().state(RespStatus.PARAM_ERROR).message("好友请求不存在");
            return false;
        }
        // 创建好友（带验证）
        Friend friend = getFriend(friendRequest, loginUserId);
        if (friend == null) return false;

        // 新增好友
        int added = friendMapper.add(friend);
        // 更新好友请求状态
        int updated = friendRequestMapper.updateVerifyStatus(id, 1);
        if (added != 1 || updated != 1) throw new ApplicationException(RespStatus.FAIL, "系统错误，新增失败");
        return true;
    }

    @Override
    @Transactional(rollbackFor = ApplicationException.class)
    public boolean refuse(Long id) {
        // 获取登录用户id
        Long loginUserId = SecurityUtil.getUserId();

        // 获取好友请求信息
        FriendRequest friendRequest = friendRequestMapper.getById(id);
        // 好友请求不存在
        if (friendRequest == null) {
            ResultBuild.result().state(RespStatus.PARAM_ERROR).message("好友请求不存在");
            return false;
        }
        // 校验是发给登录用户的请求
        Long toUser = friendRequest.getToUser();
        if (!toUser.equals(loginUserId)) {
            ResultBuild.result().state(RespStatus.PARAM_ERROR).message("好友请求接收者与当前登录用户不符");
            return false;
        }

        // 拒绝
        int updated = friendRequestMapper.updateVerifyStatus(id, 2);
        if (updated != 1) throw new ApplicationException(RespStatus.FAIL, "系统错误，拒绝请求失败");
        return true;
    }

    @Override
    public List<UserVo> findFriendByUserId(Long userId) {
        List<Long> ids = friendMapper.getByUserId(userId);
        return userService.findByIds(ids);
    }

    @Override
    public List<UserVo> findOnline(Long userId) {
        List<UserVo> friends = this.findFriendByUserId(userId);
        return friends.stream().filter(userVo -> Objects.equals(LoginStatus.ONLINE, userVo.getStatus())).toList();
    }

    @Override
    @Transactional(rollbackFor = ApplicationException.class)
    public boolean remove(Long friendId) {
        // 获取登录用户
        Long loginUserId = SecurityUtil.getUserId();

        // 校验登录用户与目标用户是好友
        if (friendMapper.getByBothSides(loginUserId, friendId) == null) {
            ResultBuild.result().state(RespStatus.NOT_FOUND).message("无好友关系，无法删除好友");
            return false;
        }

        // 删除相关好友请求
        int deleted1 = friendRequestMapper.deleteByBothSides(loginUserId, friendId);
        // 删除好友关系
        int deleted2 = friendMapper.deleteByBothSides(loginUserId, friendId);
        if (deleted1 != 1 || deleted2 != 1) throw new ApplicationException(RespStatus.FAIL, "系统错误，删除失败");
        return true;
    }
}
